package org.lgiavedoni.android.franq.service.analytic;

import org.lgiavedoni.android.franq.core.service.Service;
import org.lgiavedoni.android.franq.service.config.ConfigService;
import org.lgiavedoni.android.franq.service.config.ConfigService.ConfigKey;
import org.lgiavedoni.android.franq.service.log.Logger;
import org.lgiavedoni.android.franq.service.phone.ContextService;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

public class AnalyticService extends Service {

	public static final AnalyticService inst = new AnalyticService();
	private GoogleAnalyticsTracker tracker;

	private AnalyticService() {
	}

	@Override
	public String getServiceName() {
		return "analytic";
	}

	@Override
	protected void startInternal() {
		if (ContextService.inst.isApplicationContextLoaded()) {
			tracker = GoogleAnalyticsTracker.getInstance();
			tracker.start(ConfigService.inst.getValue(ConfigKey.ANALYTIC_CODE), ContextService.inst.getApplicationContext());
		} else {
			setStatus(Service.Status.ERROR);
		}
		AnalyticService.inst.trackIni();
	}

	@Override
	protected void stopInternal() {
		if (tracker != null) {
			tracker.stop();
			tracker = null;
		}
	}

	@Override
	public void _run() {
	}

	public void trackIni() {
		try {
			if (isStarted())
				tracker.trackPageView("/startingApplication");
		} catch (Exception e) {
			Logger.inst.error(e);
		}
	}

	public void trackError(String error) {
		try {
			if (isStarted())
				tracker.trackEvent("ERROR", "ERROR", error, 1);
		} catch (Exception e) {
			Logger.inst.error(e);
		}
	}

}